package com.speedy.course.widget

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import androidx.core.content.res.use
import com.speedy.course.R
import com.speedy.course.ext.dp2px

class Divider @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) :
    View(context, attrs)  {

    private var dividerColor: Int = Color.WHITE

    private val paint by lazy {
        Paint().apply {
            style = Paint.Style.FILL
        }
    }

    init {
        try{
            context.obtainStyledAttributes(R.styleable.Divider).use {
                dividerColor = it.getColor(
                    R.styleable.Divider_dividerColor,
                    context.getColor(R.color.dividerColor)
                )
            }
        }catch (e:Exception){
            e.printStackTrace()
        }

        paint.color = dividerColor
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        var widthSpec = widthMeasureSpec
        if (MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY) {
            widthSpec = MeasureSpec.makeMeasureSpec(context.dp2px(0.5F), MeasureSpec.EXACTLY)
        }
        var heightSpec = heightMeasureSpec
        if (MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY) {
            heightSpec = MeasureSpec.makeMeasureSpec(context.dp2px(0.5F), MeasureSpec.EXACTLY)
        }
        super.onMeasure(widthSpec, heightSpec)
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas?.apply {
            drawLine(0F, 0F, width.toFloat(), height.toFloat(), paint)
        }
    }

    companion object {

    }
}